package com.itjin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.mapper.DialogLogMapper;
import com.itjin.model.domain.dto.DialogDTO;
import com.itjin.model.domain.entity.DialogLog;
import com.itjin.model.domain.vo.EmotionAnalysisVO;
import com.itjin.model.result.Result;
import com.itjin.service.AIanalysisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * AI心理分析服务实现类
 */
@Service
@Slf4j
public class AIanalysisServiceImpl extends ServiceImpl<DialogLogMapper, DialogLog> implements AIanalysisService {

  @Resource
  private RestTemplate restTemplate;

  @Resource
  private DialogLogMapper dialogLogMapper;

  private static final String SHISA_AI_API_URL = "https://openrouter.ai/api/v1/chat/completions";
  private static final String SHISA_AI_API_KEY = "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";
  private static final String SHISA_AI_MODEL = "shisa-ai/shisa-v2-llama3.3-70b:free";
  private static final String SITE_URL = "https://yourapplication.com";
  private static final String SITE_NAME = "User Center Application";

  /**
   * 情绪分析枚举值，用于解析AI返回的情绪标签
   */
  private static final List<String> EMOTION_TYPES = Arrays.asList(
      "joy", "sadness", "anger", "fear", "disgust", "surprise",
      "trust", "anticipation", "anxiety", "stress", "depression",
      "confidence", "excitement", "relief", "satisfaction");

  @Override
  public Result<EmotionAnalysisVO> analyzeDialog(DialogDTO dialogDTO) {
    if (dialogDTO == null || dialogDTO.getDialogContents() == null || dialogDTO.getDialogContents().trim().isEmpty()) {
      return Result.failure(400, "对话内容不能为空");
    }

    try {
      // 1. 获取用户提问内容
      String userQuestion = dialogDTO.getDialogContents();

      // 2. 调用AI进行情绪分析
      Map<String, Double> emotionAnalysis = analyzeEmotionWithAI(userQuestion);
      if (emotionAnalysis == null || emotionAnalysis.isEmpty()) {
        return Result.failure(500, "情绪分析失败");
      }

      // 3. 获取情感分析建议
      String suggestion = getSuggestionWithAI(userQuestion, emotionAnalysis);

      // 4. 根据内容和情绪自动确定对话类型
      int dialogType = determineDialogType(userQuestion, emotionAnalysis);

      // 5. 生成AI的回复
      String aiResponse = generateAIResponse(userQuestion, emotionAnalysis, dialogType);

      // 6. 保存对话记录 - 使用新的保存方法确保数据完整性
      DialogLog dialogLog = saveDialogRecord(
          dialogDTO.getUserId(), userQuestion, aiResponse, emotionAnalysis, dialogType);

      // 7. 构建返回结果
      // 找出情绪分值最高的类型
      String primaryEmotion = getPrimaryEmotion(emotionAnalysis);

      // 计算综合情绪得分 (0-100)
      int emotionScore = calculateEmotionScore(emotionAnalysis);

      EmotionAnalysisVO analysisVO = EmotionAnalysisVO.builder()
          .dialogId(dialogLog.getId())
          .userId(dialogDTO.getUserId())
          .dialogContents(userQuestion)
          .dialogAsk(aiResponse)
          .emotionScores(emotionAnalysis)
          .primaryEmotion(primaryEmotion)
          .emotionScore(emotionScore)
          .suggestions(suggestion)
          .dialogType(dialogType)
          .build();

      return Result.success(analysisVO);

    } catch (Exception e) {
      log.error("分析对话失败", e);
      return Result.failure(500, "分析对话失败: " + e.getMessage());
    }
  }

  @Override
  public Result<List<DialogLog>> getUserDialogHistory(Integer userId) {
    if (userId == null || userId <= 0) {
      return Result.failure(400, "用户ID不合法");
    }

    try {
      // 使用自定义查询方法获取历史记录
      List<DialogLog> dialogLogs = dialogLogMapper.getUserDialogHistory(userId);

      // 安全处理：不返回完整对话内容，只返回摘要信息
      dialogLogs.forEach(dialog -> {
        // 如果对话内容超过50个字符，截断并添加省略号
        String content = dialog.getDialogContents();
        if (content != null && content.length() > 50) {
          dialog.setDialogContents(content.substring(0, 50) + "...");
        }
      });

      return Result.success(dialogLogs);
    } catch (Exception e) {
      log.error("获取用户对话历史失败", e);
      return Result.failure(500, "获取对话历史失败: " + e.getMessage());
    }
  }

  @Override
  public Result<DialogLog> getDialogDetail(Integer dialogId) {
    if (dialogId == null || dialogId <= 0) {
      return Result.failure(400, "对话ID不合法");
    }

    try {
      // 使用自定义查询方法，确保获取所有字段
      DialogLog dialogLog = dialogLogMapper.getDialogWithEmotionById(dialogId);
      if (dialogLog == null) {
        return Result.failure(404, "对话记录不存在");
      }

      // 如果情感分析为空，提供一个默认的空对象
      if (dialogLog.getEmotionAnalysis() == null) {
        log.warn("对话ID {} 的情感分析结果为空，使用空对象", dialogId);
        dialogLog.setEmotionAnalysis(new HashMap<>());
      }

      return Result.success(dialogLog);
    } catch (Exception e) {
      log.error("获取对话详情失败", e);
      return Result.failure(500, "获取对话详情失败: " + e.getMessage());
    }
  }

  @Override
  public Result<Map<String, Object>> getUserEmotionTrend(Integer userId, Integer days) {
    if (userId == null || userId <= 0) {
      return Result.failure(400, "用户ID不合法");
    }

    if (days == null || days <= 0) {
      days = 7; // 默认查询7天
    }

    try {
      // 计算日期范围
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_MONTH, -days);
      Date startDate = calendar.getTime();

      // 查询指定日期范围内的对话记录
      QueryWrapper<DialogLog> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("userId", userId)
          .ge("createTime", startDate)
          .eq("isDelete", 0)
          .orderByAsc("createTime");

      List<DialogLog> dialogLogs = dialogLogMapper.selectList(queryWrapper);

      // 构建情绪趋势数据
      Map<String, Object> trendData = new HashMap<>();

      // 日期标签
      List<String> dateLabels = new ArrayList<>();

      // 情绪类型计数
      Map<String, List<Double>> emotionTrends = new HashMap<>();
      for (String emotionType : EMOTION_TYPES) {
        emotionTrends.put(emotionType, new ArrayList<>());
      }

      // 情绪得分趋势
      List<Integer> emotionScores = new ArrayList<>();

      // 按日期分组处理数据
      Map<String, List<DialogLog>> dialogsByDate = dialogLogs.stream().collect(
          Collectors.groupingBy(dialog -> {
            Calendar cal = Calendar.getInstance();
            cal.setTime(dialog.getCreateTime());
            return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
          }));

      // 确保所有日期都有数据
      Calendar tempCal = Calendar.getInstance();
      tempCal.setTime(startDate);

      for (int i = 0; i <= days; i++) {
        String dateStr = tempCal.get(Calendar.YEAR) + "-" + (tempCal.get(Calendar.MONTH) + 1) + "-"
            + tempCal.get(Calendar.DAY_OF_MONTH);
        dateLabels.add(dateStr);

        List<DialogLog> dayDialogs = dialogsByDate.getOrDefault(dateStr, new ArrayList<>());

        if (dayDialogs.isEmpty()) {
          // 如果当天没有对话，所有情绪值为0
          emotionScores.add(0);
          for (String emotionType : EMOTION_TYPES) {
            emotionTrends.get(emotionType).add(0.0);
          }
        } else {
          // 计算当天平均情绪值
          int avgScore = 0;
          Map<String, Double> avgEmotions = new HashMap<>();

          for (DialogLog dialog : dayDialogs) {
            Map<String, Double> emotions = dialog.getEmotionAnalysis();
            if (emotions != null) {
              for (String emotion : EMOTION_TYPES) {
                double value = emotions.getOrDefault(emotion, 0.0);
                avgEmotions.put(emotion, avgEmotions.getOrDefault(emotion, 0.0) + value);
              }

              avgScore += calculateEmotionScore(emotions);
            }
          }

          // 计算平均值
          int dialogCount = dayDialogs.size();
          for (String emotion : EMOTION_TYPES) {
            double avgValue = avgEmotions.getOrDefault(emotion, 0.0) / dialogCount;
            emotionTrends.get(emotion).add(avgValue);
          }

          emotionScores.add(avgScore / dialogCount);
        }

        tempCal.add(Calendar.DAY_OF_MONTH, 1);
      }

      trendData.put("dates", dateLabels);
      trendData.put("emotionTrends", emotionTrends);
      trendData.put("emotionScores", emotionScores);

      return Result.success(trendData);

    } catch (Exception e) {
      log.error("获取用户情绪趋势失败", e);
      return Result.failure(500, "获取情绪趋势失败: " + e.getMessage());
    }
  }

  @Override
  public Result<Boolean> deleteDialog(Integer dialogId, Integer userId) {
    if (dialogId == null || dialogId <= 0) {
      return Result.failure(400, "对话ID不合法");
    }

    if (userId == null || userId <= 0) {
      return Result.failure(400, "用户ID不合法");
    }

    try {
      // 先检查记录是否存在且属于该用户
      QueryWrapper<DialogLog> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("id", dialogId)
          .eq("userId", userId)
          .eq("isDelete", 0);

      DialogLog dialogLog = dialogLogMapper.selectOne(queryWrapper);
      if (dialogLog == null) {
        return Result.failure(404, "对话记录不存在或无权限删除");
      }

      // 执行逻辑删除
      boolean removed = this.removeById(dialogId);
      return Result.success(removed);

    } catch (Exception e) {
      log.error("删除对话记录失败", e);
      return Result.failure(500, "删除对话记录失败: " + e.getMessage());
    }
  }

  /**
   * 使用AI分析对话内容的情绪
   * 
   * @param content 对话内容
   * @return 情绪分析结果
   */
  private Map<String, Double> analyzeEmotionWithAI(String content) {
    try {
      String promptTemplate = "你是一位心理学专家，请对以下文本进行多维度的情绪分析。" +
          "将分析结果按以下情绪类型给出对应的分值（0-1之间的小数，保留两位小数），" +
          "分析结果仅返回JSON格式，不要有任何其他文本。\n\n" +
          "情绪类型：\n" +
          "- joy（喜悦）\n" +
          "- sadness（悲伤）\n" +
          "- anger（愤怒）\n" +
          "- fear（恐惧）\n" +
          "- disgust（厌恶）\n" +
          "- surprise（惊讶）\n" +
          "- trust（信任）\n" +
          "- anticipation（期待）\n" +
          "- anxiety（焦虑）\n" +
          "- stress（压力）\n" +
          "- depression（抑郁）\n" +
          "- confidence（自信）\n" +
          "- excitement（兴奋）\n" +
          "- relief（释然）\n" +
          "- satisfaction（满足）\n\n" +
          "对话内容：" + content + "\n\n" +
          "请仅返回JSON格式的分析结果，不要有其他文字说明。例如：\n" +
          "{\"joy\": 0.85, \"sadness\": 0.12, ...}";

      // 构建HTTP请求
      HttpHeaders headers = createAIRequestHeaders();

      // 创建消息体
      Map<String, Object> message = new HashMap<>();
      message.put("role", "user");
      message.put("content", promptTemplate);

      List<Map<String, Object>> messages = new ArrayList<>();
      messages.add(message);

      // 创建请求体
      Map<String, Object> requestBody = new HashMap<>();
      requestBody.put("model", SHISA_AI_MODEL);
      requestBody.put("messages", messages);
      requestBody.put("max_tokens", 1024);
      requestBody.put("temperature", 0.3); // 低温度值，保证输出一致性

      // 发送请求
      HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
      Map<String, Object> response = restTemplate.postForObject(SHISA_AI_API_URL, entity, Map.class);

      // 解析响应
      if (response != null && response.containsKey("choices")) {
        List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
        if (!choices.isEmpty()) {
          Map<String, Object> choice = choices.get(0);
          Map<String, Object> messageResponse = (Map<String, Object>) choice.get("message");
          if (messageResponse != null && messageResponse.containsKey("content")) {
            String responseContent = (String) messageResponse.get("content");

            // 提取JSON部分
            Map<String, Double> emotionAnalysis = extractJsonFromResponse(responseContent);
            return emotionAnalysis;
          }
        }
      }

      log.error("情绪分析API返回异常：{}", response);
      return new HashMap<>();
    } catch (Exception e) {
      log.error("调用AI进行情绪分析失败", e);
      return new HashMap<>();
    }
  }

  /**
   * 根据对话内容和情绪自动确定对话类型
   * 1-普通对话 2-心理咨询 3-情绪疏导
   */
  private int determineDialogType(String content, Map<String, Double> emotionAnalysis) {
    try {
      // 计算消极情绪总分
      double negativeEmotionScore = 0;
      List<String> negativeEmotions = Arrays.asList(
          "sadness", "anger", "fear", "disgust", "anxiety", "stress", "depression");

      for (String emotion : negativeEmotions) {
        negativeEmotionScore += emotionAnalysis.getOrDefault(emotion, 0.0);
      }

      // 检查内容是否包含心理咨询关键词
      List<String> counselingKeywords = Arrays.asList(
          "抑郁", "焦虑", "压力", "心理医生", "咨询师", "精神", "治疗", "自杀", "绝望",
          "失眠", "心理问题", "trauma", "创伤", "ptsd", "心理健康", "精神健康");

      boolean containsCounselingKeywords = counselingKeywords.stream()
          .anyMatch(keyword -> content.toLowerCase().contains(keyword.toLowerCase()));

      // 根据消极情绪得分和关键词判断类型
      if (containsCounselingKeywords ||
          (negativeEmotionScore > 1.5)) { // 多个高强度消极情绪
        return 2; // 心理咨询
      } else if (negativeEmotionScore > 0.8) { // 存在明显消极情绪
        return 3; // 情绪疏导
      } else {
        return 1; // 普通对话
      }
    } catch (Exception e) {
      log.error("确定对话类型失败，使用默认类型", e);
      return 1; // 默认为普通对话
    }
  }

  /**
   * 根据对话内容和情绪分析结果，获取AI建议
   */
  private String getSuggestionWithAI(String content, Map<String, Double> emotionAnalysis) {
    try {
      // 构建情绪分析结果字符串
      StringBuilder emotionStr = new StringBuilder();
      for (Map.Entry<String, Double> entry : emotionAnalysis.entrySet()) {
        emotionStr.append(entry.getKey()).append(": ").append(entry.getValue()).append(", ");
      }

      String primaryEmotion = getPrimaryEmotion(emotionAnalysis);

      String promptTemplate = "你是一位专业的心理咨询师，请根据以下对话内容和情绪分析结果，" +
          "提供一段简短的心理建议（不超过200字）。建议应当温暖、专业，避免生硬或教条的表达，" +
          "让用户感受到被理解和支持。\n\n" +
          "对话内容：" + content + "\n\n" +
          "情绪分析结果：" + emotionStr.toString() + "\n" +
          "主要情绪：" + primaryEmotion + "\n\n" +
          "请直接给出建议，不要有任何引言或总结，不要加任何引号或其他特殊符号。";

      // 构建HTTP请求
      HttpHeaders headers = createAIRequestHeaders();

      // 创建消息体
      Map<String, Object> message = new HashMap<>();
      message.put("role", "user");
      message.put("content", promptTemplate);

      List<Map<String, Object>> messages = new ArrayList<>();
      messages.add(message);

      // 创建请求体
      Map<String, Object> requestBody = new HashMap<>();
      requestBody.put("model", SHISA_AI_MODEL);
      requestBody.put("messages", messages);
      requestBody.put("max_tokens", 1024);
      requestBody.put("temperature", 0.7); // 适中温度值，保证一定的创造性

      // 发送请求
      HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
      Map<String, Object> response = restTemplate.postForObject(SHISA_AI_API_URL, entity, Map.class);

      // 解析响应
      if (response != null && response.containsKey("choices")) {
        List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
        if (!choices.isEmpty()) {
          Map<String, Object> choice = choices.get(0);
          Map<String, Object> messageResponse = (Map<String, Object>) choice.get("message");
          if (messageResponse != null && messageResponse.containsKey("content")) {
            String suggestion = (String) messageResponse.get("content");
            // 清理建议文本，移除可能的引号
            return cleanSuggestionText(suggestion);
          }
        }
      }

      return "暂无建议";
    } catch (Exception e) {
      log.error("获取AI建议失败", e);
      return "系统暂时无法提供建议";
    }
  }

  /**
   * 清理建议文本，移除引号和其他不需要的符号
   */
  private String cleanSuggestionText(String text) {
    if (text == null) {
      return "";
    }

    // 移除开头和结尾的引号
    text = text.trim();
    if (text.startsWith("\"") && text.endsWith("\"")) {
      text = text.substring(1, text.length() - 1);
    }

    // 逐个移除各种引号字符
    text = text.replace("\"", "");
    text = text.replace("'", "");

    return text.trim();
  }

  /**
   * 创建AI请求头
   */
  private HttpHeaders createAIRequestHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer " + SHISA_AI_API_KEY);
    headers.set("HTTP-Referer", SITE_URL);
    headers.set("X-Title", SITE_NAME);
    return headers;
  }

  /**
   * 从AI响应中提取JSON数据
   */
  private Map<String, Double> extractJsonFromResponse(String response) {
    try {
      // 查找JSON开始的位置
      int startPos = response.indexOf('{');
      int endPos = response.lastIndexOf('}');

      if (startPos >= 0 && endPos > startPos) {
        String jsonStr = response.substring(startPos, endPos + 1);
        // 使用Jackson解析JSON
        return new com.fasterxml.jackson.databind.ObjectMapper().readValue(
            jsonStr,
            new com.fasterxml.jackson.core.type.TypeReference<Map<String, Double>>() {
            });
      }

      log.warn("无法从响应中提取JSON: {}", response);
      return new HashMap<>();
    } catch (Exception e) {
      log.error("解析JSON失败", e);
      return new HashMap<>();
    }
  }

  /**
   * 获取情绪分值最高的类型
   */
  private String getPrimaryEmotion(Map<String, Double> emotionAnalysis) {
    if (emotionAnalysis == null || emotionAnalysis.isEmpty()) {
      return "unknown";
    }

    String primaryEmotion = null;
    double maxScore = -1;

    for (Map.Entry<String, Double> entry : emotionAnalysis.entrySet()) {
      if (entry.getValue() > maxScore) {
        maxScore = entry.getValue();
        primaryEmotion = entry.getKey();
      }
    }

    return primaryEmotion != null ? primaryEmotion : "unknown";
  }

  /**
   * 计算综合情绪得分 (0-100)
   * 积极情绪高分，消极情绪低分
   */
  private int calculateEmotionScore(Map<String, Double> emotionAnalysis) {
    if (emotionAnalysis == null || emotionAnalysis.isEmpty()) {
      return 50; // 默认中性分数
    }

    // 积极情绪
    List<String> positiveEmotions = Arrays.asList(
        "joy", "trust", "anticipation", "confidence", "excitement", "relief", "satisfaction");

    // 消极情绪
    List<String> negativeEmotions = Arrays.asList(
        "sadness", "anger", "fear", "disgust", "anxiety", "stress", "depression");

    double positiveScore = 0;
    double negativeScore = 0;

    // 计算积极情绪得分
    for (String emotion : positiveEmotions) {
      positiveScore += emotionAnalysis.getOrDefault(emotion, 0.0);
    }

    // 计算消极情绪得分
    for (String emotion : negativeEmotions) {
      negativeScore += emotionAnalysis.getOrDefault(emotion, 0.0);
    }

    // 标准化到0-100范围
    if (positiveScore + negativeScore > 0) {
      int score = (int) (100 * positiveScore / (positiveScore + negativeScore));
      // 限制在0-100范围内
      return Math.max(0, Math.min(100, score));
    }

    return 50; // 默认中性分数
  }

  /**
   * 加密对话内容
   * 注意：实际生产环境请使用更安全的加密方法
   */
  private String encryptContent(String content) {
    // 此处仅作示例，实际需要接入更安全的加密算法
    try {
      // 假设存在EncryptionUtil工具类
      return content; // 此处不做真实加密，仅返回原内容
      // return EncryptionUtil.encrypt(content);
    } catch (Exception e) {
      log.error("加密对话内容失败", e);
      return content;
    }
  }

  /**
   * 解密对话内容
   */
  private String decryptContent(String encryptedContent) {
    // 此处仅作示例，实际需要接入对应的解密算法
    try {
      // 假设存在EncryptionUtil工具类
      return encryptedContent; // 此处不做真实解密，仅返回原内容
      // return EncryptionUtil.decrypt(encryptedContent);
    } catch (Exception e) {
      log.error("解密对话内容失败", e);
      return encryptedContent;
    }
  }

  /**
   * 生成AI的回复内容
   */
  private String generateAIResponse(String userQuestion, Map<String, Double> emotionAnalysis, int dialogType) {
    try {
      // 构建情绪分析结果字符串
      StringBuilder emotionStr = new StringBuilder();
      for (Map.Entry<String, Double> entry : emotionAnalysis.entrySet()) {
        emotionStr.append(entry.getKey()).append(": ").append(entry.getValue()).append(", ");
      }

      String primaryEmotion = getPrimaryEmotion(emotionAnalysis);
      String dialogTypeStr = dialogType == 1 ? "普通对话" : (dialogType == 2 ? "心理咨询" : "情绪疏导");

      String promptTemplate = "你是一位AI心理助手，请根据以下用户问题和情绪分析结果，" +
          "生成一个适合的回复。你的回复应当温暖、专业，展现出理解和关心。\n\n" +
          "用户问题：" + userQuestion + "\n\n" +
          "情绪分析结果：" + emotionStr.toString() + "\n" +
          "主要情绪：" + primaryEmotion + "\n" +
          "对话类型：" + dialogTypeStr + "\n\n" +
          "请直接给出回复，语气要温和、体贴，不要有任何引言或总结，不要添加任何引号或其他特殊符号。";

      // 构建HTTP请求
      HttpHeaders headers = createAIRequestHeaders();

      // 创建消息体
      Map<String, Object> message = new HashMap<>();
      message.put("role", "user");
      message.put("content", promptTemplate);

      List<Map<String, Object>> messages = new ArrayList<>();
      messages.add(message);

      // 创建请求体
      Map<String, Object> requestBody = new HashMap<>();
      requestBody.put("model", SHISA_AI_MODEL);
      requestBody.put("messages", messages);
      requestBody.put("max_tokens", 1024);
      requestBody.put("temperature", 0.8); // 适中偏高温度值，保证回复的创造性

      // 发送请求
      HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
      Map<String, Object> response = restTemplate.postForObject(SHISA_AI_API_URL, entity, Map.class);

      // 解析响应
      if (response != null && response.containsKey("choices")) {
        List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
        if (!choices.isEmpty()) {
          Map<String, Object> choice = choices.get(0);
          Map<String, Object> messageResponse = (Map<String, Object>) choice.get("message");
          if (messageResponse != null && messageResponse.containsKey("content")) {
            String aiResponse = (String) messageResponse.get("content");
            // 清理文本
            return cleanSuggestionText(aiResponse);
          }
        }
      }

      return "抱歉，我现在无法回答您的问题。请稍后再试。";
    } catch (Exception e) {
      log.error("生成AI回复失败", e);
      return "抱歉，系统暂时无法生成回复。";
    }
  }

  /**
   * 保存对话记录和情感分析结果
   */
  private DialogLog saveDialogRecord(Integer userId, String dialogContents, String dialogAsk,
      Map<String, Double> emotionAnalysis, int dialogType) {
    DialogLog dialogLog = new DialogLog();
    dialogLog.setUserId(userId);
    dialogLog.setDialogContents(dialogContents);
    dialogLog.setDialogAsk(dialogAsk);
    dialogLog.setDialogType(dialogType);
    dialogLog.setEmotionAnalysis(emotionAnalysis);
    dialogLog.setCreateTime(new Date());
    dialogLog.setUpdateTime(new Date());
    dialogLog.setIsDelete(0);

    // 确保情感分析结果不为空
    if (emotionAnalysis == null || emotionAnalysis.isEmpty()) {
      log.warn("情感分析结果为空，使用默认值");
      dialogLog.setEmotionAnalysis(new HashMap<>());
    }

    boolean saved = this.save(dialogLog);
    if (!saved) {
      log.error("保存对话记录失败");
      throw new RuntimeException("保存对话记录失败");
    }

    // 重新查询以确保所有字段正确加载
    return dialogLogMapper.selectById(dialogLog.getId());
  }
}
